#include <windows.h>
#include "ServiceInstaller.h"
#include "BridgeService.h"
#include "BridgeManager.h"
#include "CtrlManager.h"
#include "Logger.h"

int main(int argc, char* argv[])
{
    WSADATA wsaData;

    int nRes = WSAStartup(MAKEWORD(1, 1), &wsaData);
    if (nRes != 0) {
        switch (nRes) {
        case WSASYSNOTREADY:
            Logger::Error("try reboot system");
            break;
        case WSAVERNOTSUPPORTED:
            Logger::Error("try update network library");
            break;
        }
        return -1;
    }

    setvbuf(stdout, NULL, _IONBF, 0);
    BridgeManager* manager = new BridgeManager();

    BOOL bRunAsService = FALSE;
    if (!bRunAsService) {
        CtrlManager* ctrlManager = new CtrlManager(manager);
        ctrlManager->Start();

        manager->LoadFromDB();
        manager->StartAll();

        //Sleep(2000);
        //ctrlManager->Stop();
        //manager->StopAll();

        ctrlManager->WaitingForStopped();
    }
    else {
        BridgeService service;
        if (argc > 1) {
            if (strcmp(argv[1], "install") == 0) {
                if (!ServiceInstaller::Install(service)) {
                    Logger::Error("Couldn't install service: %d", ::GetLastError());
                    return -1;
                }

                Logger::Info("Service installed");
                return 0;
            }

            if (strcmp(argv[1], "uninstall") == 0) {
                if (!ServiceInstaller::Uninstall(service)) {
                    Logger::Error("Couldn't uninstall service: %d", ::GetLastError());
                    return -1;
                }

                Logger::Info("Service uninstalled");
                return 0;
            }

            Logger::Error("Invalid argument");
            return -1;
        }
        service.Run(manager);
    }

    delete manager;

    WSACleanup();

    return 0;
}